package com.dy.分类.链表.分隔链表;
/*
给定一个链表和一个特定值 x，对链表进行分隔，使得所有小于 x 的节点都在大于或等于 x 的节点之前。

你应当保留两个分区中每个节点的初始相对位置。

示例:

输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5

 */

/**
 * 注意：使用无值头节点可以更简单
 */
class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}


public class Solution {
    public ListNode partition(ListNode head, int x) {
        ListNode lessHead = new ListNode(0);
        ListNode l = lessHead;
        ListNode moreHead = new ListNode(0);
        ListNode m = moreHead;
        ListNode p = head;
        while (p != null) {
            if (p.val < x) {
                l.next = p;

                p = p.next;
                l = l.next;
                l.next = null;

            } else {
                m.next = p;
                p = p.next;
                m = m.next;
                m.next = null;
            }
        }
        l.next = moreHead.next;
        return lessHead.next;
    }

    public static void main(String[] args) {
        ListNode lessHead = new ListNode(1);
        lessHead.next = new ListNode(4);
        lessHead.next.next = new ListNode(3);
        lessHead.next.next.next = new ListNode(2);
        lessHead.next.next.next.next = new ListNode(5);
        lessHead.next.next.next.next.next = new ListNode(2);
        Solution solution = new Solution();
        solution.partition(lessHead,3);
        System.out.println();
    }
}
